package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.FilterChain;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.Filter;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher RPATH_MATCHE = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求的URI
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/front/**",
                "/user/login"};
        boolean check = check(request.getRequestURI(), urls);//获取在check中的方法拿到这次的对比结果
        if (check) {
            log.info("本次请求不需要拦截"+request.getRequestURI());//如果为true放行如果为false拦截
            filterChain.doFilter(request, response);
            return;
        }
        boolean a = request.getSession().getAttribute("employee") != null;
        boolean b = request.getSession().getAttribute("user") != null;
        if (a) {
            BaseContext.setThreadLocal((Long)request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }else if(b){
            BaseContext.setThreadLocal((Long)request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        log.info("拦截成功"+request.getRequestURI());//如果为true放行如果为false拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean check(String Path, String[] arr) {
        for (String s : arr) {
            boolean a = RPATH_MATCHE.match(s, Path);
            if (a) {
                return true;

            }
        }
        return false;

    }
}
